package com.mes.web.controller.hy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.mes.entity.hy.Equipment;
import com.mes.entity.jy.Productroom;
import com.mes.entity.tdd.Staff;
import com.mes.service.hy.IEquipmentService;
import com.mes.service.jy.CarRoomServise;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;

/**
 * 
 * @ClassName:EquController
 * @Description:
 * @Author hy
 * @Date 2018-3-8上午11:20:48
 * @version 1.0
 */
@Controller
@RequestMapping("/equipment")
public class EquController {
	
	@Resource
	private IEquipmentService iEquipmentService;
	
	@Resource
	private CarRoomServise carRoomServise;
	
	String limit1;
	String offset1;

	/**
	 * 条件分页查询
	 * @param response
	 * @param request
	 * @param limit	每页显示的行数
	 * @param offset 页码
	 * @param equipment 设备类
	 * @throws Exception
	 */
	@RequestMapping("select")
	public void equOth(HttpServletResponse response,HttpServletRequest request,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			Equipment equipment) throws Exception {
		// 全局变量赋值，做当前页导出用
		limit1 = limit;
		offset1 = offset;
		Date now = new Date();
		Date abandonedtime = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (!"".equals(offset)) {
			equipment.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		}
		equipment.setPageSize(Integer.parseInt(limit));
		//转码
		if (!("").equals(equipment.getEqenter())
				&& equipment.getEqenter().equals(
						new String(equipment.getEqenter()
								.getBytes("iso-8859-1"), "utf-8"))) {
			equipment.setEqenter(new String(equipment.getEqenter().getBytes(
					"iso-8859-1"), "utf-8"));
		}
		if (!("").equals(equipment.getName())
				&& equipment.getName().equals(
						new String(equipment.getName().getBytes("iso-8859-1"),"utf-8"))) {
			equipment.setName(new String(equipment.getName().getBytes(
					"iso-8859-1"), "utf-8"));
		}
		if (!("").equals(equipment.getFactory())
				&& equipment.getFactory().equals(
						new String(equipment.getFactory()
								.getBytes("iso-8859-1"), "utf-8"))) {
			equipment.setFactory(new String(equipment.getFactory().getBytes(
					"iso-8859-1"), "utf-8"));
		}
		
		List<Equipment> equList = iEquipmentService.equOth(equipment);
		if (equList.size() > 0) {
			for (int i = 0; i < equList.size(); i++) {
				// 从集合中取出车间id转为long类型，通过jyy的这个方法去查属于这个id的对象
				Productroom productroom = new Productroom();
				if (!"".equals(equList.get(i).getWorkshop())
						&& equList.get(i).getWorkshop() != null) {
					productroom = carRoomServise.selectCarRoomByid(Long
							.parseLong(equList.get(i).getWorkshop()));
				}
				// 从对象中获取车间名称放入list集合中供前台显示
				if (productroom != null) {
					equList.get(i).setWorkshop(productroom.getName());
				}
				// 判断废弃时间
				if (equList.get(i).getAbandonedtime() != null
						&& !"".equals(equList.get(i).getAbandonedtime())) {
					abandonedtime = sdf
							.parse(equList.get(i).getAbandonedtime());
					// 判断时间大小
					if (abandonedtime.before(now)) {
						equList.get(i).setRemark2("3");
					} else {
						equList.get(i).setRemark2("1");
					}
				} else {
					equList.get(i).setRemark2("1");
				}
			}
		}
		int total = iEquipmentService.equCount();
		// 判断长度，避免显示空白页
		if (equList.size() == 0) {
			equipment.setPage(equipment.getPage() - 1);
			equList = iEquipmentService.equOth(equipment);
		}
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(equList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * id查询
	 * @param response
	 * @param equipment 设备类
	 * @throws Exception
	 */
	@RequestMapping("/equiSelByID")
	public void equiSelByID(HttpServletResponse response, Equipment equipment)
			throws Exception {
		Equipment equipment2 = iEquipmentService.selectById(equipment);

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(equipment2, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 删除
	 * @param response
	 * @param eids 设备id
	 * @throws Exception
	 */
	@RequestMapping("/equiDel")
	public void equiDel(HttpServletResponse response, String eids)
			throws Exception {
		int total = 0;
		String[] eid = eids.split(",");
		for (int i = 0; i < eid.length; i++) {
			total += iEquipmentService.delete(Long.parseLong(eid[i]));
		}
		ResponseUtil.write(response, total);
	}

	/**
	 * 修改
	 * @param response
	 * @param equipment 设备类
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/update")
	public void update(HttpServletResponse response, Equipment equipment,
			HttpServletRequest request) throws Exception {
		// 修改成功
		String flag = "1";
		// 判断session
		HttpSession session = request.getSession();
		// 从session中取出用户身份信息
		Staff userSession = (Staff) session.getAttribute("staff");
		if(userSession != null){
			equipment.setEqenter(userSession.getStaffname());
		}
		
		Date now = new Date();
		Date abandonedtime = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		equipment.setEqentertime(sdf.format(now));
		if (equipment.getAbandonedtime() != null
				&& !"".equals(equipment.getAbandonedtime())) {
			abandonedtime = sdf.parse(equipment.getAbandonedtime());
			// 判断时间大小
			if (abandonedtime.before(now)) {
				equipment.setRemark2("3");
			} else {
				equipment.setRemark2("1");
			}
		} else {
			equipment.setRemark2("1");
		}
		iEquipmentService.update(equipment);
		ResponseUtil.write(response, flag);
	}

	/**
	 * 添加
	 * @param response
	 * @param equipment 设备类
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/addEqui")
	public void addEqui(HttpServletResponse response, Equipment equipment,
			HttpServletRequest request) throws Exception {
		// 判断session
		HttpSession session = request.getSession();
		// 从session中取出用户身份信息
		Staff userSession = (Staff) session.getAttribute("staff");
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.format(now);
		String flag = "1";
		int count = iEquipmentService.equOth(equipment).size();
		if (count > 0) {
			// 已存在
			flag = "2";
		} else {
			try {
				// 为1时表示"闲置",2为使用中,3为废弃
				equipment.setRemark2("1");
				if(userSession != null){
					equipment.setEqenter(userSession.getStaffname());
				}
				equipment.setEqentertime(dateFormat.format(now));
				iEquipmentService.addEqui(equipment);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		ResponseUtil.write(response, flag);
	}

	/**
	 * 查询所有
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selAll")
	public void selAll(HttpServletResponse response) throws Exception {
		List<Equipment> list = iEquipmentService.selAll();
		Productroom productroom = new Productroom();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getRemark2().equals("1")) {
				list.get(i).setRemark2("闲置");
			} else if (list.get(i).getRemark2().equals("2")) {
				list.get(i).setRemark2("使用中");
			} else {
				list.get(i).setRemark2("废弃");
			}
			if(list.get(i).getWorkshop() != null && !"".equals(list.get(i).getWorkshop())){
				productroom = carRoomServise.selectCarRoomByid(Long.parseLong(list
						.get(i).getWorkshop()));
			}
			// 加判断，防止关联表中没数据或数据不对查不出结果
			if (productroom != null) {
				list.get(i).setWorkshop(productroom.getName());
			}
		}
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 导出当前页
	 * @param response
	 * @param equipment 设备类
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping("/export")
	public void export(HttpServletResponse response, Equipment equipment)
			throws Exception {
		if (!"".equals(offset1)) {
			equipment.setPage(Integer.parseInt(offset1)
					/ Integer.parseInt(limit1));
		}
		equipment.setPageSize(Integer.parseInt(limit1));
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("当前页设备信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("设备名称");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("吨位");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("型号");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("购置日期");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("安装日期");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("设备生产厂家");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("废弃日期");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("状态");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("录入人");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("设备所处车间");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("录入时间");
		cell.setCellStyle(style);
		// 导出当前页
		List<Equipment> list = iEquipmentService.equOth(equipment);
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Equipment equipment2 = list.get(i);
			row.createCell(0).setCellValue(i + 1);
			row.createCell(1).setCellValue(equipment2.getName());
			row.createCell(2).setCellValue(equipment2.getTonnage());
			row.createCell(3).setCellValue(equipment2.getVersion());
			row.createCell(4)
					.setCellValue(equipment2.getPurchasedate());
			row.createCell(5).setCellValue(
					equipment2.getInstallationdate());
			row.createCell(6).setCellValue(equipment2.getFactory());
			row.createCell(7).setCellValue(
					equipment2.getAbandonedtime());
			row.createCell(8).setCellValue(equipment2.getRemark2());
			row.createCell(9).setCellValue(equipment2.getEqenter());
			row.createCell(10).setCellValue(equipment2.getWorkshop());
			row.createCell(11)
					.setCellValue(equipment2.getEqentertime());
			row.createCell(12).setCellValue(equipment2.getRemark());
			row.createCell(13).setCellValue(equipment2.getRemark1());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "设备信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出所有
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/exportAll")
	public void exportAll(HttpServletResponse response) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("所有设备信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("设备名称");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("吨位");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("型号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("购置日期");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("安装日期");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("废弃日期");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("生产厂家");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("车间");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("录入人");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("录入时间");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("状态");
		cell.setCellStyle(style);
		// 导出所有
		List<Equipment> list = iEquipmentService.selAll();
		Productroom productroom = new Productroom();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getRemark2().equals("1")) {
				list.get(i).setRemark2("闲置");
			} else if (list.get(i).getRemark2().equals("2")) {
				list.get(i).setRemark2("使用中");
			} else {
				list.get(i).setRemark2("废弃");
			}
			productroom = carRoomServise.selectCarRoomByid(Long.parseLong(list
					.get(i).getWorkshop()));
			// 加判断，防止关联表中没数据或数据不对查不出结果
			if (productroom != null) {
				list.get(i).setWorkshop(productroom.getName());
			}
		}
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Equipment equipment2 = list.get(i);
			row.createCell(0).setCellValue(equipment2.getName());
			row.createCell(1).setCellValue(equipment2.getTonnage());
			row.createCell(2).setCellValue(equipment2.getVersion());
			row.createCell(3)
					.setCellValue(equipment2.getPurchasedate());
			row.createCell(4).setCellValue(
					equipment2.getInstallationdate());
			row.createCell(5).setCellValue(
					equipment2.getAbandonedtime());
			row.createCell(6).setCellValue(equipment2.getFactory());
			row.createCell(7).setCellValue(equipment2.getWorkshop());
			row.createCell(8).setCellValue(equipment2.getEqenter());
			row.createCell(9).setCellValue(equipment2.getEqentertime());
			row.createCell(10).setCellValue(equipment2.getRemark2());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "设备信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导入
	 * @param file 导入对象
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException, IOException {
		String savePath = ((HttpSession) request).getServletContext().getRealPath(
				"/WEB-INF/" + file.getOriginalFilename());
		File newFile = new File(savePath);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		// 取文件后缀
		String subfix = savePath.lastIndexOf(".") == -1 ? "" : savePath
				.substring(savePath.lastIndexOf(".") + 1);
		List<List<String>> lists = new ArrayList<>();
		// 获取导入行数
		List<String> names = names();
		int num = names.size();
		String str = "xls";
		String strx = "xlsx";
		if (subfix.equals(str)) {
			lists = ExcelUtils.readXls(savePath, request, num + 1);
		} else if (subfix.equals(strx)) {
			lists = ExcelUtils.readXlsx(savePath, request, num + 1);
		} else {
			response.getWriter().print("0");
		}
		Productroom productroom = new Productroom();
		int count = 0;
		int flag = 1;
		for (int i = 0; i < lists.size(); i++) {
			List<String> list = new ArrayList<>();
			list = lists.get(i);
			Equipment equipment = new Equipment();
			equipment.setName(list.get(0) == null ? "" : list.get(0));
			equipment.setTonnage(list.get(1) == null ? "" : list.get(1));
			equipment.setVersion(list.get(2) == null ? "" : list.get(2));
			equipment.setPurchasedate(list.get(3) == null ? "" : list.get(3));
			equipment.setInstallationdate(list.get(4) == null ? "" : list
					.get(4));
			equipment.setFactory(list.get(5) == null ? "" : list.get(5));
			productroom = carRoomServise.selCarRoomByName(list.get(6));
			if (productroom == null) {
				equipment.setWorkshop("");
			} else {
				equipment.setWorkshop(String.valueOf(productroom.getId()) == null ? ""
								: String.valueOf(productroom.getId()));
			}
			// 添加功能
			iEquipmentService.addEqui(equipment);
			count++;
		}
		if (count == 0) {
			flag = -1;
		}
		response.getWriter().print(flag);
	}

	/**
	 * 导入模板表头
	 * @return
	 */
	public List<String> names() {
		List<String> list = new ArrayList<>();
		list.add("设备名称");
		list.add("吨位");
		list.add("型号");
		list.add("购置日期");
		list.add("安装日期");
		list.add("生产厂家");
		list.add("车间");
		return list;
	}

	/**
	 * 导出模板
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ExcelUtils.exportFile("设备信息导入模板", names(), response);
	}
}
